package hw_7_31.serializable_Demo2;


import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TestApp {
    private static final String FILE_PATH = "data/b.txt";
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student(1,"张三",19,78));
        studentList.add(new Student(2,"李四",20,90));
        studentList.add(new Student(3,"王五",30,84));
        serializeObjects(studentList);
        System.out.println("学生对象序列化完成！");
        List<Student> studentList1 = deserializeStudents();
        for (Student student : studentList1) {
            System.out.println("学号：" + student.getId() + ",姓名：" + student.getName() + ",年龄：" +
                    student.getAge() + ",分数：" + student.getScore());
        }
    }

    public static void serializeObjects(List<Student> students){
        File file = new File(FILE_PATH);
        if (!file.exists()){
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            for (Student student : students) {
                oos.writeObject(student);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<Student> deserializeStudents(){
        List<Student> students = new ArrayList<>();
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(FILE_PATH)))) {
            while (true){
                try {
                    Object obj = ois.readObject();
                    students.add((Student) obj);
                } catch (EOFException e) {
                    break; // 读取到文件末尾，退出循环
                }
            }
            System.out.println("学生信息反序列化完成！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return students;
    }
}
